/**
 * 适应范围：公共函数   CRM系统
 * 作者：林超群
 * 日期：2011-11-19
 * 版本：v1.0.0
 * 修改：
 */

var ES = ES || {};
//常用正则
ES.Reg = {
	EMAIL:/\w+([.-_]\w+)*@\w+([.-_]\w+)*\.\w{2,4}/,			//邮箱
	CN:/^[\u4e00-\u9fa5]*$/,								//中文
	EN:/^[a-zA-Z]*$/,										//字母
	NUM:/^[0-9]*$/,											//数字
	SINT:/^[1-9]\d*$/,										//正整数
	SFLOAT:/^[1-9]\d*.\d*|0.\d*[1-9]\d*$/,					//正浮点数
	MONEY:/^((([1-9]\d*)|0)(\.\d{1,2})?)$/					//money格式
	//NOZEROMONEY:/^((([1-9]\d*)|0)(\.\d{1,2})?)$/			//money格式
};
//浏览器判断
ES.BS = {
	Version: navigator.appVersion,  //浏览器的版本，一般不与实际的浏览器版本对应
	Opera: !!window.opera, //Opera支持
	WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,  //userAgent 浏览器的用户代理字符串
	Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
	Win: navigator.userAgent.indexOf('Windows') >= 0
};
//提供cookie添加、查询和删除操作
ES.Cookie = {
	/**
	 * 添加Cookie
	 * @param {String}  sName  cookie名
	 * @param {String}  sValue  cookie值
	 * @param {String}  sExpires  过期时间
	 * @param {String}	sPath    指定cookie的路径
	 * @param {String}	sDomain	  指定可访问cookie的主机名
	 * @param {Boolean} bSecure	  是否加密
	 */
	setCookie: function (sName, sValue, sExpires, sPath, sDomain, bSecure) {
		var sCookie = sName + '=' + encodeURIComponent(sValue);
		sExpires && (sCookie += '; expires=' + sExpires);
		sPath && (sCookie += '; path=' + sPath);
		sDomain && (sCookie += '; domain=' + sDomain);
		bSecure && (sCookie += '; secure');
		document.cookie = sCookie;
	},
	/**
	 * 获得Cookie
	 * @param {String}  sName   cookie名
	 * @return {String}  cookie值
	 */
	getCookie: function (sName) {
		var sRE = '(?:; )?' + sName + '=([^;]*);?';
		var oRE = new RegExp(sRE);
		if (oRE.test(document.cookie)) {
			return decodeURIComponent(RegExp['$1']);
		} else {
			return null;
		}
	},
	/**
	 * 删除Cookie
	 * @param {String}	sName	cookie名
	 * @param {String}  sPath	cookie路径
	 * @param {String}	sDomain	cookie主机名
	 */
	delCookie: function (sName, sPath, sDomain) {
		var sCookie = sName + '=; expires=' + (new Date(0)).toGMTString();
		sPath && (sCookie += '; path=' + sPath);
		sDomain && (sCookie += '; domain=' + sDomain);
		document.cookie = sCookie;
	},
	/**
	 * 获取正确的Cookie有郊时间
	 * @param {Number} days   天
	 * @param {Number} hours  小时
	 * @param {Number} minutes  分
	 * @retrun {String} GMTString
	 */
	getExpDate: function(days, hours, minutes) {
		var expDate = new Date();
		if(typeof days === 'number' && typeof hours === 'number' && typeof minutes === 'number') {
			expDate.setDate(expDate.getDate() + parseInt(days));
			expDate.setHours(expDate.getHours() + parseInt(hours));
			expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
			return expDate.toGMTString();
		}
	}
};
//提供图片的加载
ES.Img = {
	/**
	 * 检测图片是否存在（用于图片上传后续显示前的判断，避免出现请求返回404错误）
	 * @param {String} url 图片URL
	 * @param {Number} loadTime 尝试重复加载次数，如果不设定值，默认为5次
	 * @param {Function} fSuccess 图片存在时的回调函数
	 * @param {Function} fError 图片不存在时的回调函数
	 */
	loadCheck: function(sURL, nLoadTime, fSuccess, fError) {
		var img = new Image();
		//console.log(typeof fSuccess);
		//初始数参数
		//if(undefined === window.tmpInnit) {
		sURL = ('string' === typeof sURL) ? sURL : '';
		nLoadTime = (('number' === typeof nLoadTime) ? nLoadTime : 5) - 1;
		fSuccess = ('function' === typeof fSuccess) ? fSuccess : function() {
			return;
		};
		fError = ('function' === typeof fError) ? fError : function() {
			return;
		};
		//}
		//加载监听
		if (!!(window.attachEvent && !window.opera)) {
			img.onreadystatechange = function() {
				if (img.readyState == 'complete' || img.readyState == 'loaded') {
					//return true;
					fSuccess();
				}
			}
		} else {
			img.onload = function() {
				if (img.complete == true) {
					//return true;
					fSuccess();
				}
			}
		}
		//如果因为网络或图片的原因发生异常，则显示该图片
		//一定要先把src、error和onload清空
		img.onerror = function() {
			if (0 < nLoadTime) {
				nLoadTime --;
				this.src = undefined;
				this.onerror = null;
				this.onload = null;
				this.onreadystatechange = null;
				//console.log('请求图片失败，可能图片路径错误或图片不存在，再请求。');
				ES.Img.loadCheck(sURL, nLoadTime, fSuccess, fError);
			} else {
				//window.nImgTime = 0;
				this.onerror = null;
				this.onload = null;
				this.onreadystatechange = null;
				//console.log('请求图片失败，终止请求。');
				fError();
				//return false;
			}
		};
		img.src = sURL;
	},
	/**
	 * 设置缺失图片
	 * @param {Object} me 需要设置缺失图片的对象
	 * @param {String} sImgurl 缺失图片路径
	 */
	defalutImage: function(me, sImgurl) {
		//me.src = sImgurl;
		ES.Img.loadCheck(sImgurl, 2, function() {
			me.src = sImgurl;
		});
	}
};
//JSON解析
ES.JSON = {
	/**
	 * JSON解析
	 * @param {String} JSON格式字符串
	 * @return {Object} 对象
	 */
	parse: function(sJSON){
		if(typeof JSON !== 'undefined'){
			return JSON.parse(sJSON);
		}else{
			return eval('(' + sJSON + ')');
		}
	}
};
//URL相关操作
ES.Url = {
	/**
	 * 获取URL参数
	 * @return {Object} 返回是一个包含所有URL参数的Object
	 */
	getParams: function() {
		//name = name || '';
		var urlParam = window.location.search.substr(1);
		var params = {};
		if ('' != urlParam) {
			urlParam = urlParam.split('&');
			for(var i = 0; i < urlParam.length; i ++) {
				params[urlParam[i].split('=')[0]] = unescape(urlParam[i].split('=')[1]);
			}
		}
		return params;
	},
	urlEncode: function(sKeyWord) {
		var aEncodeillegalChars = ['%25', '%26', '*', '%3F', '%3A', '%3C', '%3E', '%23', '%5C', '%2F', '%7C', '%22', '%2B', '_', '.'];
		var aIllegalChars = ['%', '&', '*', '?', ':', '>', '<', '#', '\\', '\/', '|', '"', '+',  '_', '.']; //Url中包含这些字符没法进aspnet_iisapi,#如法取到AbsolutePath只包括#的前部分
		var sEncodeStrs = encodeURIComponent(sKeyWord.replace(/(^\s)|(\s$)/g, ''));
		for (var i = 0, len = aEncodeillegalChars.length; i < len; i++) {
			var rx = new RegExp('\\' + aEncodeillegalChars[i], 'ig');
			sEncodeStrs = sEncodeStrs.replace(rx, '=' + aIllegalChars[i].charCodeAt(0).toString(16).toUpperCase());
		}
		return sEncodeStrs;
	},
	UrlDecode: function(keyWord) {
		var aEncodeillegalChars = ['%25', '%26', '*', '%3F', '%3A', '%3C', '%3E', '%23', '%5C', '%2F', '%7C', '%22', '%2B', '_', '.'];
		var aIllegalChars = ['%', '&', '*', '?', ':', '>', '<', '#', '\\', '\/', '|', '"', '+',  '_', '.']; //Url中包含这些字符没法进aspnet_iisapi,#如法取到AbsolutePath只包括#的前部分
		var sEncodeStrs = keyWord;
		for (var i = 0, len = aIllegalChars.length; i < aIllegalChars.length; i++) {
			var rx = new RegExp("=" + aIllegalChars[i].charCodeAt(0).toString(16).toUpperCase(), "ig");
            sEncodeStrs = sEncodeStrs.replace(rx, aEncodeillegalChars[i]);
		}
		sEncodeStrs = decodeURIComponent(sEncodeStrs);
		return sEncodeStrs;
	}
};
ES.Tools = {};
//JQ库下的公共函数
if(typeof $ !== 'undefined') {
	/**
	 * 全选
	 * @param {JQ Object} oChkSwitch  全选开关JQ对象集
	 * @param {{JQ Object} oChkList    实施全选的checkbox对象集
	 */
	ES.Tools.selectChk = function(oChkSwitch, oChkList) {
		oChkSwitch.click( function() {
			var me = $(this);
			if(me.attr('checked')) {
				oChkSwitch.attr('checked','checked');
				oChkList.not(':checked').attr('checked','checked');
			} else {
				oChkSwitch.attr('checked','')
				oChkList.filter(':checked').attr('checked','');
			}
		});
	};
	/**
	 * 输入过滤
	 * @param {JQ Object}	oInput  监听对象
	 * @param {RegExp}	rule	过滤规则
	 */
	ES.Tools.filterInput = function(oInput, rule) {
		oInput.keyup( function() {
			var me = $(this);
			me.val(me.val().replace(rule,''));
		});
	};
}
/**
 * 替换字符串
 * @return {String} 替换后的字符串
 */
ES.Tools.stringFormat = function() {
	if(!arguments.length)
		return null;
	var str = arguments[0],
	o = arguments.length - 1;
	for(var i = 1; i <= o; i ++) {
		str = str.replace(/\#\{[\w-\s]*\}/, arguments[i]);
	}
	return str;
};
/**
 * 获取keyCode值（兼容各大浏览器）
 * @param {Object} e 事件对象
 * @return {String} keyCode
 */
ES.Tools.getKeyCode = function(e) {
	return e.keyCode || e.which || e.charCode;
};
ES.Maths = {
	/**
	 * 小数截取
	 * @param {Number} src 源小数
	 * @param {Number} pos 保留长度
	 * @return {Number}
	 */
	formatFloat: function(src, pos) {
		return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
	},
	/**
	 * 数字格式化
	 * @param {Number} s
	 * @return {String}
	 */
	formatNumber: function(s) {
		if(/[^0-9\.\-]/.test(s)) {
			return "0";
		}
		s = ES.Maths.formatFloat(s, 2);
		s = (s + '').replace(/^(\d*)$/, '$1.');
		s = (s + '00').replace(/(\d*\.\d\d)\d*/,'$1');
		s = s.replace('.', ',');
		var re = /(\d)(\d{3},)/;
		while(re.test(s)) {
			s = s.replace(re,'$1,$2');
		}
		s = s.replace(/,(\d\d)$/,'.$1');
		return s.replace(/^\./,'0.');
	},
	unFormatNumber: function(str) {
		return parseFloat(str.replace(/\,/g,''));
	}
};
/**
 * CRM专用
 */
ES.CRM = ES.CRM || {};
/**
 * 设置按钮失效
 */
ES.CRM.disableBtn = function(){};
/**
 * 弹出层
 * @param {Object} param  弹出层的设置参数
 * @return {Object} oDG 弹层对象
 */
ES.CRM.openPop = function(param){
	param.btnBar = (undefined == param.btnBar ? false : param.btnBar);
    window.top.oWin = window;
    window.top.oDG = new $.dialog(param);
    window.top.oDG.ShowDialog();
    return window.top.oDG;
};
/**
 * 弹出子层
 * @param {Object} param  弹出层的设置参数
 * @return {Object} oSDG 弹层对象
 */
ES.CRM.openChildPop = function(param){
	var DG = frameElement.lhgDG;
	window.top.oSWin = window;
	param.parent = DG;
	param.childCallBack = param.childCallBack || function(){};
	window.top.oSDG = new DG.curWin.$.dialog(param);
	window.top.oSDG.ShowDialog();
	window.top.oSDG.childCallBack = param.childCallBack;
	return window.top.oSDG;
};
/**
 * Alert弹出层
 * @param {String} title 弹出层标题
 * @param {String} html alert内容
 * @param {Function} callback 回调函数
 * @return {Object} 弹出层对象
 */
ES.CRM.openAlert = function(title,html,callback){
	html = '<p style="margin:15px;">' + (html || '') + '</p>';
    //window.top.winObj = window;
	var param = {
        id:'esAlert', 
        html:html, 
        title:title || '系统提示',
        btnBar:true,
        cancelBtn:false,
        height:170,
        onOK: function(){
            if(typeof callback === 'function'){
                return callback();
            }
        },
		onXclick: function(){
            if(typeof callback === 'function'){
                return callback();
            }
        }
    };
    if (frameElement && frameElement.lhgDG) {
		window.top.oDGAlert = ES.CRM.openChildPop(param);
	}else{
		window.top.oDGAlert = new $.dialog(param);
	}
    window.top.oDGAlert.ShowDialog();
    return window.top.oDGAlert;
};
/**
 * Confirm弹出层
 * @param {String} title 弹出层标题
 * @param {String} html confirm内容
 * @param {Function} okCallback 确定按钮回调函数
 * @param {Function} canelCallback 取消按钮回调函数
 * @return {Object} 弹出层对象
 */
ES.CRM.openConfirm = function(title,html,okCallback,canelCallback){
	html = '<p style="margin:15px;">' + (html || '') + '</p>';
    //window.top.winObj = window;
    var param = {
        id:'esConfirm', 
        html:html, 
        title:title || '系统提示',
        btnBar:true,
        height:170,
        onCancel: function(){
            if(typeof canelCallback === 'function'){
                 return canelCallback();
            }
        },
		onXclick: function(){
            if(typeof canelCallback === 'function'){
                 return canelCallback();
            }
        },
        onOK: function(){
            if(typeof okCallback === 'function'){
                return okCallback();
            }
        }
    };
    if (frameElement && frameElement.lhgDG) {
		window.top.oDGConfirm = ES.CRM.openChildPop(param);
	}else{
		window.top.oDGConfirm = new $.dialog(param);
	}
    window.top.oDGConfirm.ShowDialog();
    return window.top.oDGConfirm;
};
/**
 * 系统提示信息
 * @param {String} mtitle 弹出层标题
 * @param {String} mpage 内嵌页URL
 */
ES.CRM.showSystemMsg = function(mtitle, mpage){
	var t = mtitle == '' ? "系统提示" : mtitle;
    ES.CRM.openPop({ page: mpage, title: t, width: 400, height: 150 });
    setTimeout(function() {
		window.top.oDG.cancel();
    }, 3000);
};
/**
 * 系统提示信息（好像已经废弃不用了）
 */
ES.CRM.openMsg = function(time,title, html, callback){
	html = '<p style="margin:15px;">' + (html || '') + '</p>';
    //window.top.winObj = window;
    var param = {
        time:time,
        id: 'esAlerttime',
        html: html,
        title: title || '系统提示',
        btnBar: true,
        cancelBtn: false,
        height: 170,
        onOK: function () {
            if (typeof callback === 'function') {
                return callback();
            }
        },
        onXclick: function () {
            if (typeof callback === 'function') {
                return callback();
            }
        }
    };
    if (frameElement && frameElement.lhgDG) {
        window.top.oDGAlert = ES.CRM.openChildPop(param);
    } else {
        window.top.oDGAlert = new $.dialog(param);
    }
    window.top.oDGAlert.ShowDialog();
    return window.top.oDGAlert;
};
/**
 * 关闭弹出层
 * 参数：isReLoad {Boolean} 是否重新加载父页面，默认为false
 *       callback {Function} 回调函数，默认没有回调
 * 例：
        1、关闭弹出层              
        ES.CRM.closePop();

        2、关闭弹出层，并重新加载父页面
        ES.CRM.closePop({
            isReLoad: true
        });
        3、关闭弹出层，并执行回调
        ES.CRM.closePop({
            callback: fun
        });
        function fun(){};

 */
ES.CRM.closePop = function(param){
	param = $.extend({
        isReLoad: false,
        callback: null
    }, param);
    var cbFun = function () {
        typeof param.callback == 'function' && param.callback();
    };
    if (window.top.oDGAlert != null && window.top.oDGAlert.dg != null) {
        window.top.oDGAlert.cancel();
        window.top.oDGAlert = null;
        return;
    }
    if (window.top.oDGConfirm != null && window.top.oDGConfirm.dg != null) {
        window.top.oDGConfirm.cancel();
        window.top.oDGConfirm = null;
        return;
    }
    if (window.top.oSDG != null && window.top.oSDG.dg != null) {
        param.isReLoad && (window.top.oSWin.location.href = window.top.oSWin.location.href);
        cbFun();
        window.top.oSDG.cancel();
        window.top.oSDG = null;
        return;
    }
    if (window.top.oDG != null && window.top.oDG.dg != null) {
        param.isReLoad && (window.top.oWin.location.href = window.top.oWin.location.href);
        cbFun();
        window.top.oDG.cancel();
        window.top.oDG = null;
        return;
    }
};


/**
 * 保留原有使用的方法
 */
function OpenPop(param) {
	ES.CRM.openPop(param);
}

function OpenChildPop(param){
	ES.CRM.openChildPop(param);
}

function ChildCallBack(sCallBack){
	sCallBack.call(window.top.oDG.dgWin);
}

function OpenAlert(title,html,callback){
    ES.CRM.openAlert(title, html, callback);
}

function OpenConfirm(title,html,okCallback,canelCallback){
    ES.CRM.openConfirm(title,html,okCallback,canelCallback);
}

function ShowSystemMsg(mtitle, mpage) {
    ES.CRM.showSystemMsg(mtitle, mpage);
}

function OpenMsg(time,title, html, callback) {
	ES.CRM.openMsg(time,title, html, callback);
}

function closePop(param) {
    ES.CRM.closePop(param);
}


/**
 * table 数据列表 hover样式
 */
$(function(){
	$('.tb-data>tbody>tr, .tb-dg-data>tbody>tr').mouseover(function(){
		$(this).addClass('cur');
	}).mouseout(function(){
		$(this).removeClass('cur');
	});
	$('.tb-data>tbody>tr:odd, .tb-dg-data>tbody>tr:odd').addClass('odd');
	$('#tagPage>li').bind('click', function(){
	    var t = $(this);
	    t.addClass('cur').siblings().removeClass('cur');
	    $('#tagData, #tagSearch').hide();
	    $('#' + t.attr('rel') ).show();
	});
});